package com.ggk911.pharmacy_system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ggk911.pharmacy_system.entity.Role;
import com.ggk911.pharmacy_system.service.impl.RoleServiceImpl;
import com.ggk911.pharmacy_system.util.RestResult;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色控制层
 *
 * @author ggk-911
 * @version 1.0 2023/3/8 10:52
 */
@Slf4j
@RestController
@CrossOrigin
@RequiredArgsConstructor
@RequestMapping("/role")
@Api(tags = "角色控制层")
public class RoleController {
    private final RoleServiceImpl service;

    //GET查询
    @GetMapping("/queryAll")
    public RestResult queryAll(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        Page<Role> rolePage = new Page<>(page, size);
        service.page(rolePage);
        return RestResult.ok("查询成功", rolePage);
    }

    //GET获取所有数据集合
    @GetMapping("/list")
    public RestResult getList(){
        List<Role> roleList = service.list();
        return RestResult.ok("获取成功", roleList);
    }

    //PUT添加
    @PutMapping("/insert")
    public RestResult insert(Role role) {
        try {
            if (service.save(role)) {
                return RestResult.ok("添加成功，角色编号为：" + role.getRoleId(), role.getRoleId());
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        }
        return RestResult.error("添加失败");
    }

    //DELETE删除
    @DeleteMapping("/delete")
    public RestResult delete(Integer id) {
        try {
            if (service.removeById(id)) {
                return RestResult.ok("删除成功");
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        }
        return RestResult.error("删除失败");
    }

    //POST更新
    @PostMapping("/update")
    public RestResult update(Role role){
        try {
            if (service.updateById(role)) {
                return RestResult.ok("更新成功");
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        }
        return RestResult.error("更新失败");
    }
}
